/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 25228
 * Date: 2024-08-11
 * Time: 15:01
 */
class Solution {
    public String tree2str(TreeNode root) {
        StringBuilder stringBuilder=new StringBuilder();
        tree2str2(root,stringBuilder);
        return stringBuilder.toString();

    }
    public void tree2str2(TreeNode root,StringBuilder stringBuilder){
        if(root==null){
            return;
        }
        stringBuilder.append(root.val);
        if(root.left!=null){
            stringBuilder.append("(");
            tree2str2(root.left,stringBuilder);
            stringBuilder.append(")");
        }else{
            if(root.right==null){
                return;
            }else{
                stringBuilder.append("()");
            }
        }
        if(root.right!=null){
            stringBuilder.append("(");
            tree2str2(root.right,stringBuilder);
            stringBuilder.append(")");
        }else{
            return;
        }
    }
}
